package com.xiaxiang.ar.xml;

import android.util.Xml;

import org.xmlpull.v1.XmlSerializer;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by Administrator on 2017-11-13.
 */

public class XmlSerializerBuilder {
    private XmlSerializer mXmlSerializer;
    private BufferedOutputStream mOutStream;
    private final String mXmlFilePath;
    public final static String ENCODING = "utf-8";
    public final static String NAME_SPACE = null;
    public String mHomeTag;
    public XmlSerializerBuilder(String path,String homeTag){
        mXmlFilePath = path;
        mHomeTag = homeTag;
    }

    public boolean startSerializer() {
        if (mXmlSerializer != null || mOutStream != null) {
            throw new IllegalArgumentException("有正在进行的操作未finish");
        }
        //由android.util.Xml创建一个XmlSerializer实例
        mXmlSerializer = Xml.newSerializer();
        try {
            File outFile = new File(mXmlFilePath);
            if (!outFile.getParentFile().isDirectory()) {
                if (outFile.getParentFile().mkdirs()) {
                    throw new IOException("mkdirs error:" + outFile.getParentFile());
                }
            }
            mOutStream = new BufferedOutputStream(new FileOutputStream(outFile));
            //设置输出方向为out
            mXmlSerializer.setOutput(mOutStream, ENCODING);
            mXmlSerializer.startDocument(ENCODING, true);
            mXmlSerializer.startTag(NAME_SPACE, mHomeTag);
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public void writeTag(String tag,String value){
        try {
            mXmlSerializer.startTag(null, tag);
            mXmlSerializer.text(value);
            mXmlSerializer.endTag(null, tag);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public boolean finishSerializer(){
        if (mXmlSerializer == null || mOutStream == null) {
            throw new IllegalArgumentException("finish 之前需要先start");
        }
        try {
            mXmlSerializer.endTag(NAME_SPACE, mHomeTag);
            mXmlSerializer.endDocument();
            mOutStream.flush();
            mOutStream.close();
            mXmlSerializer = null;
            mOutStream = null;
            return true;
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
